﻿using System;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
using NntpClientLib;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.WebControls;

namespace NewsgroupListSync
{
    public partial class Reply : LayoutsPageBase
    {

        #region "Private Identifiers"

        protected int articleID;
        private string newsServer = "news.mathworks.com";
        private string newsGroup = "";
        private DateTime sentOn;
        private IEnumerable<string> articleBody;

        #endregion

        #region "Event Handlers"

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SPContext.Current != null)
            {
                SPWeb Web = SPContext.Current.Web;
            }

            if (!string.IsNullOrEmpty(Request.QueryString["NewsServer"]))
                newsServer = Request.QueryString["NewsServer"];
            NewsServerTextBox.Text = newsServer;

            if (!string.IsNullOrEmpty(Request.QueryString["NewsGroup"]))
                newsGroup = Request.QueryString["NewsGroup"];
            NewsGroupTextBox.Text = newsGroup;

            FromTextBox.Text = GetLoginUserEmailAddress();

            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["articleID"]))
                {
                    Int32.TryParse(Request.QueryString["articleID"], out articleID);

                    using (Rfc977NntpClient client = new Rfc977NntpClient())
                    {
                        client.Connect(newsServer);
                        client.SelectNewsgroup(newsGroup);

                        //Populate the Subject line
                        ArticleHeadersDictionary header = client.RetrieveArticleHeader(articleID);
                        SubjectTextBox.Text = "Re: " + (header.ContainsKey("Subject") ? header["Subject"][0] : "");
                        TitleLabel.Text = "Reply to " + SubjectTextBox.Text;
                        string from = header.ContainsKey("From") ? header["From"][0] : "Undefined";
                        try
                        {
                            if (header.ContainsKey("Date"))
                            {
                                IFormatProvider format = new System.Globalization.CultureInfo("en-US", true);
                                string s = header["Date"][0].Replace("(UTC)", "");
                                sentOn = DateTime.Parse(s, format);
                            }
                        }
                        catch { sentOn = DateTime.Now.ToLocalTime(); }
                        //Store in the ViewState the Message-ID for threading later during the submission
                        ViewState["Message-ID"] = (header.ContainsKey("Message-ID") ? header["Message-ID"][0] : "");

                        //Populate the Message with previous body content
                        StringBuilder sb = new StringBuilder();
                        sb.Append("\n\n\n------\n\n\n");
                        sb.Append(from + " wrote on: " + sentOn.ToString() + Environment.NewLine);
                        foreach (string body in client.RetrieveArticleBody(articleID))
                        {
                            body.Replace("=20", "");
                            body.Replace("\r\n", "");
                            body.Replace("\n", "");
                            sb.Append("> " + body + Environment.NewLine);
                        }

                        MessageTextBox.Text = sb.ToString();
                    }
                }
            }
        }

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            if (SPContext.Current != null)
            {
                MasterPageFile = SPContext.Current.Web.MasterUrl;
            }
        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["articleID"]))
            {
                Int32.TryParse(Request.QueryString["articleID"], out articleID);

                string reference = (ViewState["Message-ID"] != null) ? ViewState["Message-ID"].ToString() : "";

                try
                {

                    using (Rfc977NntpClient client = new Rfc977NntpClient())
                    {
                        client.Connect(newsServer);
                        client.SelectNewsgroup(newsGroup);

                        ArticleHeadersDictionary headers = new ArticleHeadersDictionary();

                        headers.AddHeader("From", FromTextBox.Text);
                        headers.AddHeader("Subject", SubjectTextBox.Text);
                        headers.AddHeader("Newsgroups", newsGroup);
                        //headers.AddHeader("Date", DateTime.Now.ToString());

                        if (!String.IsNullOrEmpty(reference))
                        {
                            headers.AddHeader("In-Reply-To", reference);
                            headers.AddHeader("References", reference);
                        }

                        List<string> body = new List<string>();
                        body.Add(MessageTextBox.Text);

                        client.PostArticle(new ArticleHeadersDictionaryEnumerator(headers), body);

                        //StatusLabel.Text = "Message has been replied!";
                        Response.Redirect("/_layouts/newsgroups/Thankyou.aspx?Newsgroup=" + newsGroup);
                    }
                }
                catch (Exception ex)
                {
                    StatusLabel.Text = ex.Message;
                }
            }
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(SPContext.Current.Web.Url + "/Lists/" + Regex.Replace(newsGroup, "[^A-Za-z0-9]", ""));
        }

        #endregion

        #region "Private Routines"

        private string GetLoginUserEmailAddress()
        {
            if (Context.User.Identity.IsAuthenticated)
            {
                SPUser myUser = SPContext.Current.Web.CurrentUser;
                if (myUser != null)
                    return String.Format("{0} ({1})", myUser.Email, myUser.Name);
                else
                    return "";
            }
            else
                return "";
        }

        #endregion

    }
}
